package framework.dao.mybatis.util;

import framework.dao.exception.DataAccessException;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtil {

    private static SqlSessionFactory sessionFactory;
    private static ThreadLocal<SqlSession> threadLocal;

    static{
        threadLocal=new ThreadLocal<>();

        try {
            sessionFactory=new SqlSessionFactoryBuilder()
                    .build(MyBatisUtil.class
                                      .getClassLoader()
                                      .getResourceAsStream("mybatis-config.xml"));
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("MyBatisUtil初始化失败");
        }
    }

    public static SqlSession getSession(){
        SqlSession session=null;
        try {
            session=threadLocal.get();
            if(session==null){
                session=sessionFactory.openSession();
                threadLocal.set(session);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new DataAccessException("数据访问失败",e);
        }
        return session;
    }

    public static void close(){
        SqlSession session=null;
        try {
            session=threadLocal.get();
            if(session!=null){
                session.close();
                threadLocal.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}




























